package org.zanateh.wargame.graphics;

import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.input.touch.TouchEvent;
import org.zanateh.wargame.game.Player;
import org.zanateh.wargame.game.hexagon.Hexagon;
import org.zanateh.wargame.game.piece.Piece;

public class PieceDrawable extends Rectangle {

	private boolean mGrabbed;
	private boolean mRegisteredTouch = false;
	private float mLastHexScale = 1;
	
	private float mDragOriginalPosX = 0f;
	private float mDragOriginalPosY = 0f;
	
	
	private Piece mPiece;
	
	public PieceDrawable(Piece piece) {
		super(0,0, 1f, 1f);
		mPiece = piece;
		
		Player pieceOwner = piece.getOwner();
		if( pieceOwner == null ) {
			setColor(1,1,1);
		}
		else {
			setColor(pieceOwner.r(), pieceOwner.g(), pieceOwner.b());
		}
	}
	
	public Piece getPiece()
	{
		return mPiece;
	}
	
	public void attachToHexagon(Hexagon hex) {
		if( !mRegisteredTouch ) {
			mRegisteredTouch=true;
			IEntity hexParentEntity = hex.getDrawable().getParent();
			if( Scene.class.isInstance(hexParentEntity)) {
				((Scene)hexParentEntity).attachChild(this);
				((Scene)hexParentEntity).registerTouchArea(this);
			}
			else {
				throw new IllegalArgumentException( "Unexpected parent type of HexagonDrawable (expected Scene): " + hexParentEntity.getParent().getClass().getName());
			}
		}

		mLastHexScale = hex.getDrawable().getBaseWidth()/2;
		setScale(mLastHexScale);
		this.setPosition(hex.getDrawable().getX(), hex.getDrawable().getY());

	}	
	
	public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
		switch(pSceneTouchEvent.getAction()) {
			case TouchEvent.ACTION_DOWN:
				this.setScale(1.25f * mLastHexScale);
				this.mGrabbed = true;
				this.mDragOriginalPosX = this.getX();
				this.mDragOriginalPosY = this.getY();

				this.setPosition(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
				//movePieceRelativeToParent(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
				break;
			case TouchEvent.ACTION_MOVE:
				if(this.mGrabbed) {
					this.setPosition(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
				}
				break;
			case TouchEvent.ACTION_UP:
				if(this.mGrabbed) {
					this.mGrabbed = false;

					Scene scene = (Scene)getParent();
					PointHexagonMatcher hexMatcher = new PointHexagonMatcher(this.getX(), this.getY());
					
					IEntity foundEntity = scene.findChild(hexMatcher);

					// Reset the drawable where it originally was
					this.setScale(mLastHexScale);
					this.setPosition(mDragOriginalPosX, mDragOriginalPosY);
					
					// Now generate a move request.
					if( foundEntity != null ) {
						getPiece().moveTo(((HexagonDrawable)foundEntity).getHexagon());
					}	
				}
				break;
			
		}
		return true;
	}
	
}
